 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=15 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:58 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Defensive copying
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='immutable,mutability,mutable,defensive copy,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Defensive copying</div>

<div class='main-body'>
 
<br>A mutable object is simply an object which can change its state after
construction. For example, <tt>StringBuilder</tt> and <tt>Date</tt> are
mutable objects, while <tt>String</tt> and <tt>Integer</tt> are <a href="TopicActiond838-2.html">immutable objects</a>.
<p>A class may have a mutable object as a field. There are two possible
cases for how the state of a mutable object field can change :
<ul>
<li>
its state can be changed only by the native class - the native class <i>creates</i>
the mutable object field, and is the only class which is directly aware of its existence</li>

<li>
its state can be changed both by the native class and by its callers
- the native class simply <i>points</i> to a mutable object which was created
elsewhere</li>
</ul>
Both cases are valid design choices, but you must be aware of which one
is appropriate for each case.
<p>If the mutable object field's state should be changed only by the native
class, then a <i>defensive copy </i>of the mutable object <i>must</i> be
made any time it is passed into (constructors and <tt>set</tt> methods) or out of
(<tt>get</tt> methods) the class. If this is <em>not</em> done, then it is simple for the
caller to break encapsulation, by changing the state of an object which is simultaneously visible 
to <em>both</em> the class and its caller.

<p><b>Example</b>
<p><tt>Planet</tt> has a mutable object field <tt>fDateOfDiscovery</tt>,
which is defensively copied in all constructors, and in <tt>getDateOfDiscovery</tt>.
<tt>Planet</tt>
represents an immutable class, and has no set methods for its fields. Note
that if the defensive copy of <tt>DateOfDiscovery</tt> is not made, then
<tt>Planet</tt>
is no longer immutable!
<br>
<PRE>

<span class='keyword'>import</span> java.util.Date;

<span class='comment'>/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Planet {

  <span class='keyword'>public</span> Planet (<span class='keyword'>double</span> aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     <span class='comment'>//make a private copy of aDateOfDiscovery
</span>     <span class='comment'>//this is the only way to keep the fDateOfDiscovery
</span>     <span class='comment'>//field private, and shields this class from any changes that 
</span>     <span class='comment'>//the caller may make to the original aDateOfDiscovery object
</span>     fDateOfDiscovery = <span class='keyword'>new</span> Date(aDateOfDiscovery.getTime());
  }

  <span class='comment'>/**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>double</span> getMass() {
    <span class='keyword'>return</span> fMass;
  }

  <span class='comment'>/**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */</span>
  <span class='keyword'>public</span> String getName() {
    <span class='keyword'>return</span> fName;
  }

<span class='comment'>//  /**
</span><span class='comment'>//  * Returns a mutable object - likely bad style.
</span><span class='comment'>//  *
</span><span class='comment'>//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
</span><span class='comment'>//  * since the Date object state can be changed both by this class and its caller.
</span><span class='comment'>//  * That is, this class is no longer in complete control of fDate.
</span><span class='comment'>//  */
</span><span class='comment'>//  public Date getDateOfDiscovery() {
</span><span class='comment'>//    return fDateOfDiscovery;
</span><span class='comment'>//  }
</span>
  <span class='comment'>/**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */</span>
  <span class='keyword'>public</span> Date getDateOfDiscovery() {
    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDateOfDiscovery.getTime());
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='comment'>/**
  * Final primitive data is always immutable.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>double</span> fMass;

  <span class='comment'>/**
  * An immutable object field. (String objects never change state.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;

  <span class='comment'>/**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> Date fDateOfDiscovery;
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction6f4f-2.html?Id=12'>Copy constructors</a> <br>
 
  
  <a href='TopicAction5e53-2.html?Id=22'>Fields should usually be private</a> <br>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicActioned8c-2.html?Id=71'>Avoid clone</a> <br>
 
  
  <a href='TopicActione066-2.html?Id=173'>Encapsulate collections</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='15'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=15 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:58 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
